import 'package:flutter/material.dart';
import 'package:wms/utils/utils.dart';
import '/models/LoadTaskData.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';
import '../../models/cycle_count_response.dart';

class CycleCountScreen extends StatefulWidget {
  const CycleCountScreen({super.key});

  @override
  _CycleCountScreenState createState() => _CycleCountScreenState();
}

class _CycleCountScreenState extends State<CycleCountScreen> with WidgetsBindingObserver {
  late LoadTaskData taskData;
  Map<String, dynamic>? selectedSkuItem;
  final TextEditingController locationController = TextEditingController();
  final TextEditingController skuController = TextEditingController();
  final TextEditingController quantityController = TextEditingController();
  
  // 仅保留输入框的焦点节点
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _skuFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  
  // 键盘状态管理
  bool _locationKeyboardVisible = false;
  bool _skuKeyboardVisible = false;
  bool _quantityKeyboardVisible = false;
  String? _currentFocusField;

  String? sku;
  String? oldsku;
  String? lpnNumber;
  String? shipmentCode;
  String? packKey;
  String? internalItemNumber;
  
  int? warehouseId;
  int? locationId;
  int? quantity = 0;
  String? location;
  bool buttonStatu = false;
  int? maxAllowedValue = 9999999;
  List<Map<String, dynamic>> availableSkus = [];
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;

  // 底部按钮区域高度
  static const double _buttonAreaHeight = 60;

  // Status下拉列表状态
  String selectedStatus = 'Normal';
  final List<String> statusOptions = ['Normal', 'Damaged','On Hold'];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initFocusListeners();
    
    // 初始聚焦Location
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        await _hideKeyboard();
        _focusOnField('location', showKeyboard: false);
      }
    });
    
    // SKU输入框焦点监听器
    _skuFocusNode.addListener(() {
      if (_skuFocusNode.hasFocus && skuController.text.isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          skuController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: skuController.text.length,
          );
        });
      }
      if (_skuFocusNode.hasFocus && !_skuKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 初始化焦点监听
  void _initFocusListeners() {
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
      if (_quantityFocusNode.hasFocus && !_quantityKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 焦点变化处理
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else if (_currentFocusField == field) {
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  void _showKeyboard() async => await SystemChannels.textInput.invokeMethod('TextInput.show');
  
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  void _showKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, true);
    _showKeyboard();
  });
  
  void _hideKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, false);
    _hideKeyboard();
  });
  
  void _toggleKeyboardForField(String field) {
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 聚焦方法
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'sku':
          FocusScope.of(context).requestFocus(_skuFocusNode);
          break;
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (_quantityFocusNode.context != null) {
              Scrollable.ensureVisible(
                _quantityFocusNode.context!,
                alignment: 0.4,
                duration: const Duration(milliseconds: 200),
              );
            }
          });
          break;
      }
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        _updateKeyboardState(field, false);
      }
    }
  }
  
  // 取消指定输入框焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'location': _locationFocusNode.unfocus(); break;
      case 'sku': _skuFocusNode.unfocus(); break;
      case 'quantity': _quantityFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'location': return _locationKeyboardVisible;
      case 'sku': return _skuKeyboardVisible;
      case 'quantity': return _quantityKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'location': _locationKeyboardVisible = visible; break;
        case 'sku': _skuKeyboardVisible = visible; break;
        case 'quantity': _quantityKeyboardVisible = visible; break;
      }
    });
  }
  
  // 重置所有键盘状态
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_locationKeyboardVisible && 
        !_skuKeyboardVisible && !_quantityKeyboardVisible) {
      return;
    }
    setState(() {
      _locationKeyboardVisible = false;
      _skuKeyboardVisible = false;
      _quantityKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  // 输入框点击处理
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    _focusOnField(fieldType, showKeyboard: false);
  }

  _updateButtonStatu(){
    setState(() {
      buttonStatu = skuController.text.isNotEmpty && quantityController.text.isNotEmpty;
    });
  }

  // 选择SKU处理
  void _handleSkuSelection(Map<String, dynamic> skuItem) {
    setState(() {
      if (selectedSkuItem == skuItem) {
        selectedSkuItem = null;
        packKey = null;
        internalItemNumber = null;
        skuController.clear();
        quantityController.clear();
        buttonStatu = false;
        maxAllowedValue = 9999999;
        locationId = null;
        selectedStatus = 'Normal';
      } else {
        selectedSkuItem = skuItem;
        skuController.text = skuItem['itemNumber'] ?? '';
        quantityController.text = skuItem['quantity'].toString();
        locationId = skuItem['id'];
        packKey = skuItem['packKey'];
        internalItemNumber = skuItem['internalItemNumber'];
        skuController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: skuController.text.length,
        );
        buttonStatu = true;
        selectedStatus = 'Normal';
        _focusOnField('quantity', showKeyboard: false);
      }
    });
  }

  // 处理扫描输入
  void _handleScanInput(String value) async {
    try {
      oldsku = sku;
      if(value.contains(':')){
        sku = Utils.parseQRCode(value, 'item number');
        packKey = Utils.parseQRCode(value, 'pack key');
        internalItemNumber = Utils.parseQRCode(value, 'product code');
      }

      int qty = 1;
      if(oldsku == sku && quantityController.text.isNotEmpty){
        qty += int.parse(quantityController.text);
      }
      
      setState(() {
        buttonStatu = true;
        skuController.text = sku ?? '';
        quantityController.text = qty.toString();
        selectedSkuItem = null;
        locationId = null;
        selectedStatus = 'Normal';
        if (skuController.text.isNotEmpty) {
          skuController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: skuController.text.length,
          );
        }
      });
      _focusOnField('quantity', showKeyboard: false);
    } catch (e) {
      setState(() {
        skuController.text = value;
        skuController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: value.length,
        );
      });
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 处理扫描枪输入
  _handleScanBarcode(String value) async{
    String parsedValue = value.trim();
    try {
      if(value.contains(':')){
        parsedValue = Utils.parseQRCode(value, 'location');
      }
    } catch (e) {
      print("JSON解析失败: $e");
    }
    print('parsedValue--$parsedValue');
    
    if (mounted) {
      setState(() {
        availableSkus = [];
        selectedSkuItem = null;
        skuController.clear();
        quantityController.clear();
        locationController.text = parsedValue;
        location = parsedValue;
        locationController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: parsedValue.length,
        );
        locationId = null;
        buttonStatu = false;
        selectedStatus = 'Normal';
      });
      _resetAllKeyboards();
      _focusOnField('sku', showKeyboard: false);
    }
    
    // 调用接口获取SKU列表
    final cycleResponse = await _fetchSKUsByLocation(warehouseId, location);
    if (cycleResponse.code == 2000) {
      List<Map<String, dynamic>> newSkuList = [];
      if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
        for (var detail in cycleResponse.data!) {
          newSkuList.add({
            'id': detail.id,
            'itemNumber': detail.itemNumber ?? 'N/A',
            'packType': detail.packType,
            'packKey': detail.packKey,
            'internalItemNumber': detail.internalItemNumber,
            'packTypeQuantity': detail.packTypeQuantity,
            'quantity': detail.quantity ?? 0,
          });
        }
      }
      setState(() {
        availableSkus = newSkuList;
        selectedSkuItem = null;
        skuController.clear();
        quantityController.clear();
        locationId = null;
      });
    } else {
      MessageBox.showMessageBox(context, cycleResponse.msg, isError: true);
    }
  }

  // 调用接口获取SKU列表
  Future<CycleCountResponse> _fetchSKUsByLocation(int? warehouseId, String? location) async {
    if (warehouseId == null) {
      throw Exception('Warehouse ID is missing');
    }

    final String locationParam = location != null ? '&location=$location' : '';
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchSKUsByLocation}warehouse=$warehouseId$locationParam';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      print('apiUrl---:$apiUrl');
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:$jsonData');
        return CycleCountResponse.fromJson(jsonData);
      } else if (response.statusCode == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
        throw Exception('The session has expired, Please log in again.');
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 提交处理
  _submit() async{
    try{
      _resetAllKeyboards();
      
      // 验证Location
      if (locationController.text.isEmpty) {
        MessageBox.showMessageBox(context, 'Please enter location.', isError: true);
        _focusOnField('location', showKeyboard: false);
        return;
      }
      
      // 验证数量
      quantity = int.tryParse(quantityController.text);
      if (quantity == null || quantity! <= 0) {
        MessageBox.showMessageBox(context, 'Please enter a valid quantity.', isError: true);
        _focusOnField('quantity', showKeyboard: false);
        return;
      }

      // 调用调整接口
      final result = await _adjustment();
      if(result['code'] == 2000){
        MessageBox.showMessageBox(context, result['msg']);
        
        // 重新获取SKU列表
        final cycleResponse = await _fetchSKUsByLocation(warehouseId, location);
        if (cycleResponse.code == 2000) {
          List<Map<String, dynamic>> newSkuList = [];
          if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
            for (var detail in cycleResponse.data!) {
              newSkuList.add({
                'id': detail.id,
                'itemNumber': detail.itemNumber ?? 'N/A',
                'packType': detail.packType,
                'packKey': detail.packKey,
                'internalItemNumber': detail.internalItemNumber,
                'packTypeQuantity': detail.packTypeQuantity,
                'quantity': detail.quantity ?? 0,
              });
            }
          }
          setState(() {
            availableSkus = newSkuList;
            selectedSkuItem = null;
            skuController.clear();
            quantityController.clear();
            buttonStatu = false;
            locationId = null;
            selectedStatus = 'Normal';
          });
          _focusOnField('location', showKeyboard: false);
        }
      } 
    }catch(e){
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 调整接口调用
  Future<Map<dynamic,dynamic>> _adjustment() async {
    final apiUrl = ApiService.baseURL + ApiService.cycleUpdate;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    if (packKey == null || internalItemNumber == null) {
      throw Exception('Missing SKU information');
    }
    
    try {
      var requestBody = {
        'warehouse': warehouseId,
        'location': locationController.text.trim(),
        'pack_key': packKey!.trim(),
        'internal_item_number': internalItemNumber!.trim(),
        'quantity': quantity,
        'notes' :'',
        // 'status': selectedStatus, // 接口需要时取消注释
      };
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      print('apiUrl-111--:$apiUrl');
      print('requestBody---:$requestBody');
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData-_adjustment--:${jsonData}');
        
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 构建带键盘图标的输入框通用组件
  Widget _buildKeyboardInput({
    required String fieldType,
    required TextEditingController controller,
    required FocusNode focusNode,
    required String label,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
    Function(String)? onSubmitted,
    Function(String)? onChanged,
    bool isSmallScreen = false,
  }) {
    return Row(
      children: [
        SizedBox(
          width: isSmallScreen ? 80 : 100,
          child: Text(
            '$label:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: baseFontSize * _fontScale
            ),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: SizedBox(
            height: 30,
            child: TextField(
              controller: controller,
              focusNode: focusNode,
              keyboardType: keyboardType,
              inputFormatters: inputFormatters,
              decoration: InputDecoration(
                border: const OutlineInputBorder(),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                suffixIcon: IconButton(
                  icon: Icon(
                    _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
                    color: const Color(0xFF008363),
                    size: isSmallScreen ? 18 : 20,
                  ),
                  onPressed: () => _toggleKeyboardForField(fieldType),
                  splashRadius: 20,
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints.tightFor(width: 36, height: 36),
                ),
              ),
              style: TextStyle(fontSize: baseFontSize * _fontScale),
              textInputAction: fieldType == 'location' ? TextInputAction.next : 
                               fieldType == 'sku' ? TextInputAction.next : TextInputAction.done,
              onSubmitted: onSubmitted,
              onChanged: onChanged,
              onTap: () => _onInputTap(controller, fieldType),
              onTapOutside: (event) {
                _hideKeyboardForField(fieldType);
                _unfocusField(fieldType);
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildStatusDropdown({required bool isSmallScreen}) {
  return Row(
    children: [
      SizedBox(
        width: isSmallScreen ? 80 : 100,
        child: Text(
          'Status:',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: baseFontSize * _fontScale
          ),
        ),
      ),
      const SizedBox(width: 10),
      Expanded(
        child: Container(
          height: 30,
          // 步骤1：移除容器水平内边距（改为0），由DropdownButton自身控制文字内边距
          padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
          decoration: BoxDecoration(
            border: Border.all(
              color: Colors.grey.shade400, // 与输入框默认边框颜色一致
              width: 1.0, // 与输入框边框宽度一致
            ),
            borderRadius: BorderRadius.circular(4.0), // 与输入框圆角一致
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: selectedStatus,
              isExpanded: true, // 步骤2：确保下拉框充满容器宽度
              // 步骤3：设置与输入框一致的文字内边距
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
              items: statusOptions.map((String option) {
                return DropdownMenuItem<String>(
                  value: option,
                  child: Container(
                    width: double.infinity, // 强制选项宽度充满父容器
                    child: Text(
                      option,
                      style: TextStyle(
                        fontSize: baseFontSize * _fontScale,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                );
              }).toList(),
              onChanged: (String? newValue) {
                if (newValue != null) {
                  setState(() {
                    selectedStatus = newValue;
                  });
                }
              },
              alignment: Alignment.centerLeft,
              menuMaxHeight: 200,
              style: TextStyle(
                fontSize: baseFontSize * _fontScale,
                color: Colors.black87,
              ),
            ),
          ),
        ),
      ),
    ],
  );
}

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final bottomInset = mediaQuery.viewInsets.bottom;

    return Scaffold(
      appBar: AppBar(
        title: Text('Cycle Count', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pushNamed(context, '/inventory');
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      resizeToAvoidBottomInset: true,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: _buttonAreaHeight,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 32,vertical: 16),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  return GestureDetector(
                    onTap: _resetAllKeyboards,
                    behavior: HitTestBehavior.translucent,
                    child: SingleChildScrollView(
                      padding: EdgeInsets.only(bottom: bottomInset > 0 ? bottomInset + 20 : 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // Location输入框
                          _buildKeyboardInput(
                            fieldType: 'location',
                            controller: locationController,
                            focusNode: _locationFocusNode,
                            label: 'Location',
                            onSubmitted: _handleScanBarcode,
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 20),
                          
                          // SKU列表标题
                          Text(
                            'SKUs:',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: baseFontSize * _fontScale
                            ),
                          ),
                          const SizedBox(height: 10),
                          
                          // SKU列表
                          Container(
                            height: 200,
                            constraints: BoxConstraints(maxHeight: constraints.maxHeight * 0.5),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey, width: 1.0),
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(4.0),
                              child: ListView.builder(
                                physics: const ClampingScrollPhysics(),
                                itemCount: availableSkus.length,
                                itemBuilder: (context, index) {
                                  final skuItem = availableSkus[index];
                                  final isSelected = selectedSkuItem == skuItem;
                                  
                                  return InkWell(
                                    onTap: () => _handleSkuSelection(skuItem),
                                    child: Container(
                                      margin: const EdgeInsets.symmetric(vertical: 2),
                                      decoration: BoxDecoration(
                                        border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5),
                                        borderRadius: BorderRadius.circular(4.0),
                                        color: isSelected ? Colors.green[50] : null,
                                      ),
                                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            skuItem['itemNumber'] ?? 'N/A',
                                            style: TextStyle(
                                              fontSize: listFontSize * _fontScale,
                                              fontWeight: FontWeight.bold,
                                              color: isSelected ? Colors.green : Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 6),
                                          Row(
                                            children: [
                                              Expanded(
                                                flex: 2,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'PackType: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${skuItem['packType'] ?? 'N/A'}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Expanded(
                                                flex: 2,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'PackQty: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${skuItem['packTypeQuantity'] ?? 0}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Expanded(
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Qty: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${skuItem['quantity'] ?? 0}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ),
                          const SizedBox(height: 20),
                          
                          // SKU输入框
                          _buildKeyboardInput(
                            fieldType: 'sku',
                            controller: skuController,
                            focusNode: _skuFocusNode,
                            label: 'SKU',
                            onSubmitted: _handleScanInput,
                            onChanged: (value) {
                              if (_skuFocusNode.hasFocus) {
                                skuController.selection = TextSelection(
                                  baseOffset: 0,
                                  extentOffset: value.length,
                                );
                              }
                              if (value.isNotEmpty && quantityController.text.isNotEmpty) {
                                quantityController.clear();
                              }
                              _updateButtonStatu();
                            },
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 16),
                          
                          // 数量输入框
                          _buildKeyboardInput(
                            fieldType: 'quantity',
                            controller: quantityController,
                            focusNode: _quantityFocusNode,
                            label: 'Quantity',
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              RangeInputFormatter(maxAllowedValue!)
                            ],
                            onChanged: (_) => _updateButtonStatu(),
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 16),
                          
                          // 修复后的Status下拉列表
                          _buildStatusDropdown(isSmallScreen: isSmallScreen),
                          const SizedBox(height: 20),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
          
          // Submit按钮
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            height: _buttonAreaHeight,
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 32),
              color: Theme.of(context).scaffoldBackgroundColor,
              child: Center(
                child: SizedBox(
                  width: 240,
                  height: 40,
                  child: ElevatedButton(
                    onPressed: buttonStatu ? _submit : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF008363),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: Text(
                      'Submit',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: baseFontSize * _fontScale,
                        color: Colors.white
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    
    // 移除输入框焦点监听
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _skuFocusNode.removeListener(() => _handleFocusChange('sku', _skuFocusNode));
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    
    // 释放输入框资源
    _locationFocusNode.dispose();
    _skuFocusNode.dispose();
    _quantityFocusNode.dispose();
    locationController.dispose();
    skuController.dispose();
    quantityController.dispose();
    
    super.dispose();
  }
}